package com.newgrand.service.impl;/*
 *@authot liugz
 *  @date 2023/9/20 10:56
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.newgrand.domain.model.CWBackModel;
import com.newgrand.domain.model.I8ReturnModel;
import com.newgrand.service.CntMChangeServer;
import com.newgrand.utils.HttpClientUtil;
import com.newgrand.utils.JSONValid;
import com.newgrand.utils.TimeUtils;
import com.newgrand.utils.security.Md5Utils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CntMChangeImpl implements CntMChangeServer {


    @Value("${cw.tokenUrl}")
    private String tokenUrl;
    @Value("${cw.appID}")
    private String appID;
    @Value("${cw.appKEY}")
    private String appKEY;
    @Value("${cw.appSecret}")
    private String appSecret;

    @Value("${cw.CNT.SR.addCntDChangeUrl}")
    private String addCntDChangeSRUrl;
    @Value("${cw.CNT.SR.editCntDChangeUrl}")
    private String editCntDChangeSRUrl;
    @Value("${cw.CNT.SR.delCntDChangeUrl}")
    private String delCntDChangeSRUrl;

    @Value("${cw.CNT.ZC.addCntDChangeUrl}")
    private String addCntDChangeZCUrl;
    @Value("${cw.CNT.ZC.editCntDChangeUrl}")
    private String editCntDChangeZCUrl;
    @Value("${cw.CNT.ZC.delCntDChangeUrl}")
    private String delCntDChangeZCUrl;


    private final JdbcTemplate jdbcTemplate;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public I8ReturnModel<String> sendCntMChange(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntChangeM_VIEW where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("无数据需要推送");
            }
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            boolean sta = true;//true表示新增||false表示修改
            Map<String, Object> dataMap = dataList.get(0);
            String sendUrl;
            if("1".equals(dataMap.get("szfx"))){sendUrl = addCntDChangeZCUrl;}else{sendUrl = addCntDChangeSRUrl;}
            if ("1".equals(dataMap.get("report_status")) || "2".equals(dataMap.get("report_status"))) {
                sta = false;
                dataMap.put("report_status", "-2");//赋值为中台修改状态
                if("1".equals(dataMap.get("szfx"))){sendUrl = editCntDChangeZCUrl;}else{sendUrl = editCntDChangeSRUrl;}
            }else{dataMap.put("report_status", "-1");}//删除的重修推送新增接口

            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744091");
//            新增、修改状态参数不同，单独处理 sta：true表示新增||false表示修改
            if(sta){
                map.put("data", dataMap);
            }else{
                Map<String,Object> conditionsMap = new HashMap<>();
                Map<String,Object> conditionValuesMap = new HashMap<>();
                conditionsMap.put("internal_id","=");
                conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
                map.put("values", dataMap);
                map.put("conditions", conditionsMap);
                map.put("conditionValues", conditionValuesMap);
            }

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，收入合同变更信息推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，收入合同变更信息推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    String report_rusult = "收入合同变更信息新增推送成功";//推送结果
                    String report_status = "1";
                    if(!sta){report_rusult = "收入合同同变更信息修改推送成功";report_status = "2";}
                    jdbcTemplate.update("update pcm3_cnt_change_m set user_report_status = ?, user_report_date = ?, user_report_result = ? where phid = ?",report_status, TimeUtils.getDateStr(),report_rusult, phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_change_m set  user_report_date = ?, user_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    @Async("asyncServiceExecutor")
    @Override
    public I8ReturnModel<String> sendCntMChangeBatch() {
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntChangeM_VIEW");
        for (Map<String, Object> item : dataList) {
            sendCntMChange(String.valueOf(item.get("phid")));
        }
        return I8ReturnModel.success();
    }

    @Override
    public I8ReturnModel<String> sendCntMChangeDelete(String phId) {
        try {
            List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from CntChangeM_VIEW where phid = ?", phId);
            if (dataList.isEmpty()) {
                return I8ReturnModel.success("暂无数据需删除");
            }
            Map<String, Object> dataMap = dataList.get(0);
            String sendUrl;
            if("1".equals(dataMap.get("szfx"))){sendUrl = delCntDChangeZCUrl;}else{sendUrl = delCntDChangeSRUrl;}
            dataMap.put("report_status", "-3");//赋值为中台待删除状态
            I8ReturnModel<String> returnModel = getToken();
            if (!returnModel.getIsOk()) {
                return I8ReturnModel.errorCode("401", "获取Token失败");
            }
            CWBackModel cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
            if (!"200".equals(cwBackModel.getCode())) {
                return I8ReturnModel.errorCode("401", cwBackModel.getMsg());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("dataSourceId", "469912437211140096");
            map.put("modelId", "475401302239744091");
            Map<String,Object> conditionsMap = new HashMap<>();
            Map<String,Object> conditionValuesMap = new HashMap<>();
            conditionsMap.put("internal_id","=");
            conditionValuesMap.put("internal_id",dataMap.get("internal_id"));
            map.put("conditions", conditionsMap);
            map.put("conditionValues", conditionValuesMap);

            String body = JSON.toJSONString(map);
            logger.info("phid=" + phId + "，合同变更删除推送报文：" + body);
            String tyStamp = String.valueOf(System.currentTimeMillis());
            String tySign = Md5Utils.hash(tyStamp + body + appSecret);
            Map<String, String> headers = new HashMap<>();
            headers.put("TYDTC_APP_TOKEN", cwBackModel.getData());
            sendUrl += "?tyStamp=" + tyStamp + "&tySign=" + tySign;
            returnModel = HttpClientUtil.sendPost(sendUrl, headers, body, "POST");
            logger.info("phid=" + phId + "，合同变更删除推送返回结果：" + returnModel.getData());
            if (returnModel.getIsOk() && JSONValid.isJSON2(returnModel.getData())) {
                cwBackModel = JSONObject.parseObject(returnModel.getData(), CWBackModel.class);
                if ("200".equals(cwBackModel.getCode())) {
                    jdbcTemplate.update("update pcm3_cnt_change_m set user_report_status = '3', user_report_date = ?, user_report_result = '收入合同变更删除推送成功' where phid = ?", TimeUtils.getDateStr(), phId);
                    return I8ReturnModel.success(cwBackModel.getMsg());
                }
                throw new RuntimeException(cwBackModel.getMsg());
            }
            throw new RuntimeException(returnModel.getMessage());
        } catch (Exception ex) {
            String msg = "推送失败:" + ex.getMessage();
            jdbcTemplate.update("update pcm3_cnt_change_m set user_report_date = ?, user_report_result = ? where phid = ?", TimeUtils.getDateStr(), msg, phId);
            return I8ReturnModel.errorCode("500", ex.getMessage());
        }
    }

    public I8ReturnModel<String> getToken() {
        Map<String, String> map = new HashMap<>();
        map.put("TYDTC_APP_ID", appID);
        map.put("TYDTC_APP_KEY", appKEY);
        return HttpClientUtil.sendPost(tokenUrl, map, "", "GET");
    }
}
